package com.zsrd.auth.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.laker.admin.module.sys.entity.SysPower;
//import com.laker.admin.module.sys.entity.SysRolePower;
//import com.laker.admin.module.sys.entity.SysUserRole;
//import com.laker.admin.module.sys.service.ISysMenuService;
//import com.laker.admin.module.sys.service.ISysRolePowerService;
//import com.laker.admin.module.sys.service.ISysUserRoleService;
import com.zsrd.system.domain.SysPower;
import com.zsrd.system.domain.SysRolePower;
import com.zsrd.system.domain.SysUserRole;
import com.zsrd.system.service.SysPowerService;
import com.zsrd.system.service.SysRolePowerService;
import com.zsrd.system.service.SysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    SysRolePowerService sysRolePowerService;

    @Autowired
    SysPowerService sysPowerService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginKey) {
        // 查询用户对应的角色
        List<SysUserRole> userRoles = sysUserRoleService.list(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, loginId));
        List<Integer> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        // 查询角色对应的权限
        List<SysRolePower> rolePowerLists = sysRolePowerService.list(Wrappers.<SysRolePower>lambdaQuery().in(SysRolePower::getRoleId, roleIds));
        List<Integer> powerIds = rolePowerLists.stream().map(SysRolePower::getPowerId).collect(Collectors.toList());
        // 查询权限标识
        List<SysPower> sysPowers = sysPowerService.list(Wrappers.<SysPower>lambdaQuery().in(SysPower::getMenuId, powerIds).eq(SysPower::getEnable,1));
        List<String> powers = sysPowers.stream().map(SysPower::getPowerCode).collect(Collectors.toList());
        //对超管用户跳过所有权限标识认证
        List<String> roles   = sysUserRoleService.getListRoleById(Long.parseLong((String) loginId));
        if(roles.size()>0&&roles.contains("admin")){
            powers.add("power:admin");
        }
        return powers;

    }

    /**
     * 返回一个账号所拥有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginKey) {
        List<String> roles   = sysUserRoleService.getListRoleById(Long.parseLong((String) loginId));
        return roles;
    }
}
